import sys
import math
import pandas as pd
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import QtCore
from com.atzl.common.Win import Windows
from com.atzl.common.Datas import MessagesData
from com.atzl.common.ActionStates import ActionStates
from com.atzl.functions.accounting.func.Logs import CheckLogs
from com.atzl.functions.accounting.func.SetPrice import SetPrice
from com.atzl.ui.PriceTableUI import Ui_MainWindow as pricetable

# 报价表预览窗口交互
class PriceTableWindow(QMainWindow, CheckLogs):  # 继承:QMainWindow, CheckLogs

    def __init__(self):
        QMainWindow.__init__(self)
        # 设置为全局小部件
        self.ui = pricetable()
        self.set = SetPrice()
        self.ui.setupUi(self)
        self.clipboard = QApplication.clipboard()
        self.m_flag = False
        self.text = str()
        global widgets
        widgets = self.ui
        global set
        set = self.set
        widgets.pushButton_9.clicked.connect(self.esc_this)
        widgets.pushButton_10.clicked.connect(self.showMinimized)
        widgets.tableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        widgets.tableWidget.customContextMenuRequested.connect(self.showMenu)
        self.contextMenu = QMenu(widgets.tableWidget)
        self.cpaction = self.contextMenu.addAction('复制所选内容<Ctrl+C>')
        self.tocpaction = self.contextMenu.addAction('粘贴<Ctrl+V>')
        self.contextMenu.addSeparator()
        self.openaction = self.contextMenu.addAction('打开导出所在文件夹<Ctrl+Q>')
        self.expaction = self.contextMenu.addAction('导出Excel表<Ctrl+E>')
        self.contextMenu.addSeparator()
        self.anewset = self.contextMenu.addAction('重新设置改客户报价<Ctrl+R>')
        self.affirm = self.contextMenu.addAction('确认报价<Ctrl+S>')
        self.cpaction.triggered.connect(self.table_copy)
        self.tocpaction.triggered.connect(self.table_tocopy)
        self.openaction.triggered.connect(self.open_thefiled)
        self.expaction.triggered.connect(self.export)
        self.anewset.triggered.connect(self.anewset_price)
        self.affirm.triggered.connect(self.affirm_price)
        widgets.tableWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)


    def showMenu(self, pos):  # 右键展示菜单，pos 为鼠标位置
        # 菜单显示前，将它移动到鼠标点击的位置
        self.contextMenu.exec_(QCursor.pos())  # 在鼠标位置显示
        self.logs_in(ActionStates.OPENRIGHTBUTTONMENU)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
            event.accept()
            self.setCursor(QCursor(QtCore.Qt.OpenHandCursor))  # 更改鼠标图标

    def mouseMoveEvent(self, QMouseEvent):
        if QtCore.Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)  # 更改窗口位置
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QCursor(QtCore.Qt.ArrowCursor))

    def set_table_data(self):
        df = MessagesData.SET_PRICE
        df = pd.DataFrame(df)
        y = df.shape[0]
        x = df.shape[1]
        widgets.tableWidget.setColumnCount(x - 1)
        widgets.tableWidget.setRowCount(y)
        for j in range(x-1):
            for i in range(y):
                newItem = QTableWidgetItem(str(df.iloc[i, j+1]))
                widgets.tableWidget.setItem(i, j, newItem)

                if math.ceil((i+1) / MessagesData.EXCEL_HEAD_SHPE) % 2 == 0:
                    newItem.setBackground(QBrush(QColor(0, 220, 220)))
                elif math.ceil((i+1) / MessagesData.EXCEL_HEAD_SHPE) % 2 != 0:
                    newItem.setBackground(QBrush(QColor(0, 160, 120)))
        widgets.tableWidget.update()



    def keyPressEvent(self, event):
        super().keyPressEvent(event)
        if event.key() == QtCore.Qt.Key_C \
                and (event.modifiers() & QtCore.Qt.ControlModifier):
            self.table_copy()
        elif event.key() == QtCore.Qt.Key_V \
                and (event.modifiers() & QtCore.Qt.ControlModifier):
            self.table_tocopy()
        elif event.key() == QtCore.Qt.Key_Q \
                and (event.modifiers() & QtCore.Qt.ControlModifier):
            self.open_thefiled()
            pass
        elif event.key() == QtCore.Qt.Key_E \
                and (event.modifiers() & QtCore.Qt.ControlModifier):
            # 按键事件，ctrl+e时触发，导出整张表。
            self.export()
        elif event.key() == QtCore.Qt.Key_R \
                and (event.modifiers() & QtCore.Qt.ControlModifier):
            self.anewset_price()
        elif event.key() == QtCore.Qt.Key_S \
                and (event.modifiers() & QtCore.Qt.ControlModifier):
            self.affirm_price()

    def table_copy(self):
        # 按键事件，ctrl+c时触发，复制。
        self.copied_cells = sorted(widgets.tableWidget.selectedIndexes())

        copy_text = ''
        max_column = self.copied_cells[-1].column()
        for c in self.copied_cells:
            copy_text += widgets.tableWidget.item(c.row(),
                                                  c.column()).text()
            if c.column() == max_column:
                copy_text += '\n'
            else:
                copy_text += '\t'
        QApplication.clipboard().setText(copy_text)
        self.logs_in(ActionStates.COPYOFFERTABLEDATA)

    def table_tocopy(self):
        sorted(widgets.tableWidget.selectedIndexes())
        copytext = self.clipboard.text()
        crpe = copytext.count('\t')
        crow = copytext.count('\n')
        r = widgets.tableWidget.currentRow()
        c = widgets.tableWidget.currentColumn()
        a = 0
        for i in range(crow):
            for j in range(int(crpe/crow) + 1):
                if j == int(crpe/crow):
                    solotext = copytext[a: copytext.find('\n', a)]
                    widgets.tableWidget.setItem(i + r, j + c,
                                                QTableWidgetItem(solotext))
                    a = copytext.find('\n', a) + 1
                else:
                    solotext = copytext[a: copytext.find('\t', a)]
                    widgets.tableWidget.setItem(i + r, j + c,
                                                QTableWidgetItem(solotext))
                    a = copytext.find('\t', a) + 1
        self.logs_in(ActionStates.COPYDATATOOFFERTABLE)

    def export(self):
        a = set.sql_export_excel()
        if a is True:
            self.to_message("导出成功!")
            self.logs_in(ActionStates.EXPORTOFFERTOEXCELRIGHT)
        else:
            self.to_message("导出失败!")
            self.logs_in(ActionStates.EXPORTOFFERTOEXCELERROR)

    def open_thefiled(self):
        a = set.open_files()
        if a is False:
            self.to_message("文件目录不存在!")
            self.logs_in(ActionStates.HINTDONTHAVEDIR)
        else:
            self.logs_in(ActionStates.OPENDOFFEREXCELDIR)

    def anewset_price(self):
        a = set.del_price_table(MessagesData.OBJ_ID_PRICE)
        if a is False:
            self.to_message("表不存在!")
        elif a is True:
            if MessagesData.NW_TEXT != '无':
                Windows.NWPRICETABLE_WIN.close()
            Windows.SETOFFER_WIN.show()
            self.close()
            self.logs_in(ActionStates.RESETOFFER)


    def affirm_price(self):
        Windows.SETOFFER_WIN.show()
        if MessagesData.NW_TEXT != '无':
            Windows.NWPRICETABLE_WIN.close()
        self.close()
        self.to_message("录入成功!")
        self.logs_in(ActionStates.RIGHTIMPORTOFFER)

    def esc_this(self):
        set.del_price_table(MessagesData.OBJ_ID_PRICE)
        if MessagesData.NW_TEXT != '无':
            Windows.NWPRICETABLE_WIN.close()
        self.close()
        self.logs_in(ActionStates.CLOSEOFFERTABLE)

    def to_message(self, text):
        Windows.MESSAGE_WIN.set_message(text)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = PriceTableWindow()
    window.show()
    sys.exit(app.exec_())

